package com.yunji.news.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yunji.news.common.Result;
import com.yunji.news.entity.Major;
import com.yunji.news.service.MajorService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 专业信息公共接口
 *
 * @author yunji
 * @since 2024-11-25
 */
@RestController
@RequestMapping("/majors")
@RequiredArgsConstructor
public class MajorController {

    private final MajorService majorService;

    /**
     * 分页查询专业列表
     */
    @GetMapping
    public Result<Page<Major>> getMajorPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) Long schoolId,
            @RequestParam(required = false) String name,
            @RequestParam(required = false) String category) {
        
        Page<Major> majorPage = new Page<>(page, size);
        Page<Major> result = majorService.getMajorPage(majorPage, schoolId, name, category);
        return Result.success(result);
    }

    /**
     * 获取专业详情
     */
    @GetMapping("/{id}")
    public Result<Major> getMajorDetail(@PathVariable Long id) {
        Major major = majorService.getById(id);
        if (major == null || major.getStatus() == 0) {
            return Result.error("专业不存在或已禁用");
        }
        return Result.success(major);
    }

    /**
     * 根据院校ID获取专业列表
     */
    @GetMapping("/school/{schoolId}")
    public Result<List<Major>> getMajorsBySchoolId(@PathVariable Long schoolId) {
        List<Major> majors = majorService.getMajorsBySchoolId(schoolId);
        return Result.success(majors);
    }

    /**
     * 获取专业分类列表
     */
    @GetMapping("/categories")
    public Result<List<String>> getCategories() {
        List<String> categories = majorService.getCategories();
        return Result.success(categories);
    }

    /**
     * 搜索专业
     */
    @GetMapping("/search")
    public Result<List<Major>> searchMajors(@RequestParam String keyword) {
        if (keyword == null || keyword.trim().isEmpty()) {
            return Result.error("搜索关键词不能为空");
        }
        
        Page<Major> majorPage = new Page<>(1, 20); // 限制搜索结果数量
        Page<Major> result = majorService.getMajorPage(majorPage, null, keyword.trim(), null);
        return Result.success(result.getRecords());
    }

    /**
     * 获取热门专业
     */
    @GetMapping("/popular")
    public Result<List<Major>> getPopularMajors(@RequestParam(defaultValue = "10") Integer limit) {
        // 这里可以根据实际业务逻辑来定义"热门"，比如报名人数、查看次数等
        // 目前先按创建时间倒序返回
        Page<Major> majorPage = new Page<>(1, limit);
        Page<Major> result = majorService.getMajorPage(majorPage, null, null, null);
        return Result.success(result.getRecords());
    }
}